<?php

namespace app\data\controller\api;

use app\data\service\AliMessageService;
use app\data\service\MessageService;
use app\data\service\UserAdminService;
use app\data\service\UserTokenService;
use think\admin\Controller;

/**
 * 用户登录注册接口
 * Class Login
 * @package app\data\controller\api
 */
class Login extends Controller
{
    /**
     * 接口认证类型
     * @var string
     */
    private $type;

    /**
     * 绑定数据表
     * @var string
     */
    protected $table = 'DataUser';

    /**
     * 控制器初始化
     */
    protected function initialize()
    {
        // 接收接口类型
        $this->type = $this->request->request('api');
        $this->type = $this->type ?: $this->request->header('api-name');
        $this->type = $this->type ?: $this->request->header('api-type');
        $this->type = $this->type ?: UserAdminService::API_TYPE_ANDROID;
        if (empty(UserAdminService::TYPES[$this->type])) {
            $this->error("接口支付[{$this->type}]未定义规则！");
        }
    }

    /**
     * 是否注册
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function isRegister()
    {
        $data = $this->_vali([
            'openid2.default' => '',
            'apple_openid.default' => '',
            'phone.default' => '',
            'username.default' => '',
        ]);

        if (!empty($data['openid2'])) {
            $map = ['openid2' => $data['openid2']];
        }
        if (!empty($data['apple_openid'])){
            $map = ['apple_openid' => $data['apple_openid']];
        }
        if (!empty($data['phone'])){
            $map = ['phone' => $data['phone']];
        }
        if (!empty($data['username'])){
            $map = ['username' => $data['username']];
        }
        $user = $this->app->db->name('DataUser')->where($map ?? [])->find();
        if ($user) {
            $this->success('已注册', ['is_register' => 1]);
        } else {
            $this->success('未注册', ['is_register' => 0]);
        }
    }

    /**
     * 用户统一注册入口
     * @throws \think\admin\Exception
     * @throws \think\db\exception\DbException
     */
    public function register()
    {
        $data = $this->_vali([
            'openid2.default' => '',
            'apple_openid.default' => '',
            'username.default'           => '',
            'password.default'           => '',
            'verify.default'           => '',

            'region_province.default' => '',
            'region_city.default'     => '',
            'region_area.default'     => '',
            'nickname.default'        => '',
            'base_sex.default'        => '',
            'base_birthday.default'        => '',
            'headimg.default'        => '',

            'phone.mobile'            => '手机号码格式错误！',
        ]);

        if (!empty($data['openid2'])) {
            $map = ['openid2' => $data['openid2']];
        }
        if (!empty($data['apple_openid'])){
            $map = ['apple_openid' => $data['apple_openid']];
        }
        if (!empty($data['phone'])){
            $map = ['phone' => $data['phone']];
            if (!AliMessageService::instance()->checkVerifyCode($data['verify'], $data['phone'], 'register')) {
                $this->error('短信验证失败！');
            }
        }
        if (!empty($data['username'])){
            $map = ['username' => $data['username']];
        }

        if ($this->app->db->name($this->table)->where($map ?? [])->where('deleted', 0)->count() > 0) {
            $this->error('帐号已注册，请重试！');
        }
        if (!empty($data['password'])) {
            $data['password'] = md5($data['password']);
        }
        $user = UserAdminService::instance()->set($map ?? [], $data, $this->type, true);
        empty($user) ? $this->error('手机注册失败！') : $this->success('用户注册成功！', $user);
    }

    /**
     * 用户登录接口
     * @throws \think\admin\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function in()
    {
        $data = $this->_vali([
            'type.require'    => '登录类型不能为空！',
            'type.default'    => 'password',
        ]);

        if ($data['type'] == 'password') {
            $data = array_merge($data, $this->_vali([
                'username.require'     => '帐号名称不能为空！',
                'password.require' => '密码不能为空！',
            ]));

        } else {
            $data = array_merge($data, $this->_vali([
                'username.require'     => '手机号码不能为空！',
                'username.mobile'     => '手机号码格式错误！',
                'password.require' => '验证码不能为空！',
            ]));
        }

        $user = $this->app->db->name($this->table)->where(function ($query) use ($data) {
            $query->whereOr('phone', $data['username'])->whereOr('username', $data['username']);
        })->where('deleted', 0)->find();
        if (empty($user)) $this->error('查无该帐号！');
        if (empty($user['status'])) $this->error('该用户账号状态异常！');

        if ($data['type'] == 'message' && !AliMessageService::instance()->checkVerifyCode($data['password'], $data['username'])) {
            $this->error('验证码错误，请稍候再试！');
        }

        if ($data['type'] != 'message' && md5($data['password']) !== $user['password']) {
            $this->error('密码错误，请稍候再试！');
        }

        $this->success('手机登录成功！', UserAdminService::instance()->set(['id' => $user['id'] ?? 0], [], $this->type, true));
    }

    /**
     * 第三方登录
     * @throws \WeChat\Exceptions\InvalidResponseException
     * @throws \WeChat\Exceptions\LocalCacheException
     */
    public function thirdLogin()
    {
        $data = $this->_vali([
            'type.require'    => '登录类型不能为空！',
            'type.in:openid2,apple_openid'    => '登录类型错误！',
            'openid.require'    => '用户凭证标识不能为空！',
        ]);

        $map = ['deleted' => 0, $data['type'] => $data['openid']];
        $user = $this->app->db->name($this->table)->where($map)->find();
        if (empty($user)) $this->error('该用户尚未注册哦！');
        if (empty($user['status'])) $this->error('该用户账号状态异常！');

        $this->success('登录成功！', UserAdminService::instance()->set($map, [], $this->type, true));
    }

    /**
     * 重置密码
     * @throws \think\db\exception\DbException
     */
    public function resetPassword()
    {
        $data = $this->_vali([
            'verify.require'      => '验证码不能为空',
            'password.require'      => '新密码不能为空',
            'phone.mobile'     => '手机号码格式错误！',
            'phone.require'    => '手机号码不能为空！',
        ]);

        if (!AliMessageService::instance()->checkVerifyCode($data['verify'], $data['phone'], 'reset_password')) {
            $this->error('验证码错误，请稍候再试！');
        }

        if (UserAdminService::instance()->set(['phone' => $data['phone'] ?? 0], ['password' => md5($data['password'])], $this->type, true)) {
            $this->success('重置密码成功！');
        } else {
            $this->error('重置密码失败！');
        }
    }

    /**
     * 校验token是否失效
     * @throws \think\db\exception\DbException
     */
    public function checkToken()
    {
        $token = input('token') ?: $this->request->header('Authorization');
        [$state, $info, $this->uuid] = UserTokenService::instance()->check($this->type, $token);
        if (empty($state)) $this->error($info, '{-null-}', 401);
        $this->success('token校验成功！');
    }
}